<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\common\logic;

use app\common\model\Admin;
use gdbase\Auth;
use function PHPSTORM_META\type;
use think\Db;
use think\facade\Env;
use think\Log;

class AdminLogic extends BaseLogic
{
    protected $notCheckIds=[1];//不检测权限的管理员id

    /**
     * 管理员登录
     * @param string $username 用户名
     * @param string $password 密码
     * @return bool|mixed
     */
    public function _adminLogin($username = '', $password = ''){
        $username = trim($username);
        if(empty($username)){
            return $this->retError('请输入用户名！');
        }
        $password = trim($password);
        if(empty($password)){
            return $this->retError('请输入密码！');
        }
        $query = new \think\db\Query();
        $query->where('admin_username','=',$username);
        $query->where('admin_open','=',1);
        $query->where('delete_time','=',0);
        $user = Db::name('Admin')->where($query)->find();
        if (empty($user)) {
            return $this->retError('用户不存在或被禁用！');
        }
        if (encrypt_password($password,$user['admin_pwd_salt'])!==$user['admin_pwd']) {
            return $this->retError('密码错误！');
        }
        $aid = $user['id'];
        // 更新登录信息
        $user['admin_last_ip']   = request()->ip();
        $user['admin_last_time'] = time();
        $user['admin_hits']	   = $user['admin_hits']+1;
        $jieguo = $this->save([
            'id' => $aid,
            'admin_last_ip' => $user['admin_last_ip'],
            'admin_last_time' => $user['admin_last_time'],
            'admin_hits' => $user['admin_hits'],
        ],'Admin');

        // 登录成功，显示登陆成功管理员拥有小区（项目）的列表
        $sysLogic = new SysLogic();
        if (-1 == $user['project_id']) {
            //超级管理，显示全部
            $projectList = $sysLogic->_getProjectListByWhere([],'id,name');
        }
        else{
            $projectList = $sysLogic->_getProjectListByWhere([ ['id','IN',$user['project_ids']] ],'id,name');
        }

        if(empty($projectList)){
            return $this->retError('登录成功，没有可用项目，不允许登录');
        }

        if (empty($jieguo['err_code'])) {
            // 自动登录
            $this->_auto_login($user);
        }

        // 缓存我的项目
        setMyProject($projectList);

        return $this->retSuccess('登录成功',[
            'aid'=>$aid,
            'projects'=>$projectList,
        ]);
    }

    /**
     * 自动登录
     * @param mixed $user 用户对象
     * @param bool $rememberme 是否记住登录，默认7天
     */
    public function _auto_login($user, $rememberme = false)
    {
        // 记录登录
        $auth = array(
            'aid'             			 => $user['id'],
            'project_id'             			 => $user['project_id'],
            'admin_avatar'    			 => $user['admin_avatar'],
            'admin_last_change_pwd_time' => $user['admin_changepwd'],
            'admin_realname'       		 => $user['admin_realname'],
            'admin_username'          	 => $user['admin_username'],
            'admin_last_ip' 			 => $user['admin_last_ip'],
            'admin_last_time'   		 => $user['admin_last_time']
        );
        session('admin_auth', $auth);
        session('admin_auth_sign', data_signature($auth));
    }
    /**
     * 判断是否登录
     * @return int 0或用户id
     */
    public function _is_login()
    {
        $user = session('admin_auth');
        if (empty($user)) {
            return 0;
        }else{
            if(session('admin_auth_sign') == data_signature($user)){
                return $user['aid'];
            }
            else{
                return 0;
            }
        }
    }

    /**
     * 权限检测
     * @param int
     * @return boolean
     */
    public function _checkAuth($url)
    {
        $url = strtolower($url);
        $uid = session('admin_auth.aid');
        if(in_array($uid,$this->notCheckIds)) return true;
        $urlId = $this->_getUrlId($url);
        $auth_ids_list = $this->_getAuthIds($uid);
        if(empty($auth_ids_list)) return false;
        if(in_array($urlId,$auth_ids_list)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取指定url的id(可能为显示状态或非显示状态)
     * @param string $url 为空获取当前操作的id
     * @param int $status 1表示取显示状态,为空或为0则不限制
     * @return int -1表示不需要检测 0表示无后台菜单 其他表示当前url对应id
     */
    public function _getUrlId($url,$status=0)
    {
        $authRuleList = cache('getUrlId_authRuleList','',null,'system');
        if(empty($authRuleList)){
            $authRuleList = Db::name('AuthRule')->order('level desc,sort')->select();
            cache('getUrlId_authRuleList',$authRuleList,null,'system');
        }

        $url = strtolower($url);

        if($status) {
            foreach ($authRuleList as $item) {
                if($item['status'] == $status && strtolower($item['name']) == $url){
                    return $item['id'];
                }
            }
        }
        else{
            foreach ($authRuleList as $item) {
                if(strtolower($item['name']) == $url){
                    return $item['id'];
                }
            }
        }

        return 0;

//        $menu_id = db('AuthRule')->where($where)->order('level desc,sort')->value('id');//4级或3级(如果4级,status是0,不显示)
//        $menu_id=$menu_id?:0;
//        return $menu_id;
    }

    /**
     * 获取权限菜单
     * @return array
     */
    public function _getAdminMenus()
    {
        $uid = session('admin_auth.aid');
        $menus = cache('menus_admin_'.$uid,'',null,'system');
        if($menus) return $menus;
        $where[] = ['is_del','=',0];
        $where[] = ['status','=',1];
        $where[] = ['is_menu','=',1];
        if(!in_array($uid,$this->notCheckIds)){
            $auth_ids_list = $this->_getAuthIds($uid);
            if(empty($auth_ids_list)) return [];
            $where[] = array('id','in',$auth_ids_list);
        }
        $data = db('AuthRule')->where($where)->order('sort')->select();
        $tree = new \gdbase\Tree();
        $tree->init($data,['child'=>'_child','parentid'=>'pid']);
        $menus = $tree->get_arraylist($data);
        cache('menus_admin_'.$uid,$menus,null,'system');
        return $menus;
    }

    /**
     * 获取权限菜单
     * @return array
     */
    public function _getRuelsTree($fields = '*')
    {
        $data = $this->_getRuelsList($fields);
        $tree = new \gdbase\Tree();
        $tree->init($data,['child'=>'sub','parentid'=>'pid']);
        $rst=$tree->get_arraylist($data);
        return $rst;
    }

    /**
     * 获取权限菜单
     * @return array
     */
    public function _getRuelsList($fields = '*')
    {
        return Db::name('AuthRule')->field($fields)->where('is_del',0)->order('sort')->select();
    }

    private function _getAuthIds($uid){
        $auth_ids_list = cache('auth_ids_list_'.$uid,'',null,'system');
        if(empty($auth_ids_list)){
            $auth = new Auth();
            $auth_ids_list = $auth->getAuthList($uid,1,'id');
            cache('auth_ids_list_'.$uid,$auth_ids_list,86400,'system');
        }
        return $auth_ids_list;
    }

    /**
     * 设置管理员分组
     * @param $uid
     * @param $group_id
     * @return int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _setAuthGroupAccess($uid,$group_id){
        $access = db('AuthGroupAccess')->where('uid',$uid)->find();
        if(!empty($access)){
            $jieguo = db('AuthGroupAccess')->where('uid',$uid)->setField('group_id',$group_id);
        }
        else{
            $jieguo = db('AuthGroupAccess')->insert([
                'uid'=> $uid,
                'group_id'=> $group_id,
            ]);
        }

        return $jieguo;
    }

    /**
     * 获取所有父节点id(含自身)
     * @param int $id 节点id
     * @return array
     */
    public function _getAdminParents($url)
    {
        $id = $this->_getUrlId($url,1);
        if(empty($id)) return [];
        $cacheKey = 'getAdminParents_AuthRule';
        $lists = cache($cacheKey,'',null,'system');
        if (empty($lists)) {
            $lists = db('AuthRule')->order('level desc,sort')->column('pid','id');
            cache($cacheKey,$lists,null,'system');
        }
        $ids = [];
        while (isset($lists[$id]) && $lists[$id] !=0){
            $ids[]=$id;
            $id=$lists[$id];
        }
        if(isset($lists[$id]) && $lists[$id]==0) $ids[]=$id;
        $data = array_reverse($ids);

        return $data;
    }

    /**
     * 设置用户组权限
     * @param $id
     * @param $rules
     */
    public function _setAuthGroupRules($id,$rules){
        $jieguo = db('AuthGroup')->where('id',$id)->setField('rules',$rules);

        if(false === $jieguo){
            return $this->retError('设置失败');
        }
        else{
            return $this->retSuccess('设置成功');
        }
    }

    /**
     * 添加附件
     * @param $row
     */
    public function _addAttachment($row){
        $model = $this->_getAttachmentByHash($row['md5']);
        if(empty($model)){
            $id = db('Attachment')->insertGetId($row);
        }
        else{
            $id = $model['id'];
        }
        return $id;
    }

    public function _delAttachment($path){
        $tmp = explode('/',$path);
        $title = $tmp[count($tmp) - 1];
        $tmp = explode('\\',$title);
        $title = $tmp[count($tmp) - 1];
        $model = db('Attachment')->where('title',$title)->find();
        $base_path = Env::get('ROOT_PATH') . '/public';
        if (empty($model)) {
            // 找不到数据，判断文件是否存在
            if(file_exists($base_path . $path)){
                unlink($base_path . $path);
            }
            return true;
        }
        $jieguo = db('Attachment')->where('title',$title)->delete();

        if($jieguo !== false){
            // 删除成功，删除物理文件
            if(file_exists($base_path . $path)){
                unlink($base_path . $path);
            }
        }

        return $jieguo;
    }

    public function _getAttachment($pageIndex,$pageSize = 10,$uid = 0){
        $where = [];
        if(!empty($uid)){
            $where[] = ['uid','=',$uid];
        }
        $offset = ($pageIndex - 1) * $pageSize;
        return $this->_getListByWhere($where,$offset,$pageSize,'id DESC',0,'Attachment');
    }

    /**
     * 附件重复查询
     * @param $hash
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _getAttachmentByHash($hash){
        $where[] = ['md5','=',$hash];
//        $where['status'] = 0;
        return db('Attachment')->where($where)->find();
    }

    public function _getAdminProjectIds($adminId){
        return Db::name('Admin')->where('id',$adminId)->value('project_ids');
    }
}